var page=1; //设置首页页码
var size=25;
var searchKeyWords="";
var ip="http://qure.zjgsu.edu.cn";
var totalcount1=50;
var totalcount2=50;
var totalcount3=50;
 //按钮单个禁用
 $(document).on('click', '.forbidden', function() {
                k = $(this).parents("tr").index() + 1;
                var element = this;
                var userid=this.id;
                console.log(userid);
                layui.use('layer', function() {
                    var layer = layui.layer;
                    layer.confirm('是否要禁用该人', {
                        icon: 2,
                        title: '提示'
                    }, function(index) {
                        layer.confirm('禁用后不可恢复 是否仍禁用？', {
                            icon: 2,
                            title: '提示'
                        }, function(index) {
                        $.ajax({
                            type: "PUT",
                            url: ip+"/user/offUser?userId="+userid,
                            data: {
                             	
                             },
                            async: true,
                            xhrFields: {
						withCredentials: true
						},
						crossDomain: true,
                            dataType: "json",
                            contentType: "application/json",
                            success: function(data) {
                         		$("table#teacherInfo").find("tr:eq(" + k + ")").children('td:nth-child(6)').children('.forbidden').attr('class', 'layui-btn layui-btn-disabled  layui-btn-small')
                             	layer.msg("禁用成功！")
                             	layer.close(index);
                             },
                          	Error: function() {
                                 alert("服务器出错");
                            }
                         })
                        })
                    });

                });
            })

//创建教师列表
function createTeacherList(){
	$("#peoplelist").append(
					'<div id=list1>' +

					'<table id="teacherInfo" class="display" cellspacing="0" width="100%" >\n' +
					'        <thead>\n' +
						'        <tr>\n' +
						'            <th width="10%"><input id="checkAll" class="checkAll" type="checkbox" value=""></th>\n' +
						'            <th width="20%" id="th_worknumber" >工号</th>\n' +
						'            <th width="10%" id="th_tname" >姓名</th>\n' +
						'            <th width="20%" id="th_department">部门</th>\n' +
						'            <th width="15%" id="th_telenumber" >手机</th>\n' +
						'            <th width="25%" id="th_action" >操作</th>\n' +
	
						'        </tr>\n' +
					'        </thead>\n' +
                    '        <tbody style="font-size: 14px">\n' +
					'        </tbody>\n' +
					'    </table>' +
					'</div>');

				
				
				 $('#teacherInfo').DataTable({
				 	responsive: true,
					searching:false,
			        "bLengthChange": false,
			        "bRetrieve": false,
			        'paging':false,
			        "bFilter": false, //过滤功能
			        info:false,
			        
					"columnDefs": [ 
						{ "orderable": false, "targets": 0 }
						
					]
				 });

}
//教师列表填充数据
function teacherTableDataAjax(pageconf1){
	if(!pageconf1){
		pageconf1={};
		pageconf1.pageSize=25;
		pageconf1.currentPage=1;
	}
	$.ajax({
		type:"get",
		url:ip+"/user?userTypeId=5b88e7e8dc8b5a1a84a96368&page="+pageconf1.currentPage+"&size="+pageconf1.pageSize+"&keyWord="+searchKeyWords,
		data:{},
		async:true,
		dataType:"json",
		contentType:" application/json",
		xhrFields:{withCredentials:true},
		crossDomain:true,
		success:function(res){
			console.log(res);
			$('#teacherInfo').dataTable().fnClearTable(); //清除表格内
			/*expressdata(obj.data);*/
			console.log(pageconf1);
			totalcount1=res.data.totalCount;
			console.log(totalcount1);
			getPage1(pageconf1,res.data.data);
		
	    },
		Error:function(){
			alert("服务器出错");
		}
		
	})
}




//教师列表填充数据的具体操作
function expressdata(data){
	var i=0;
	$.each(data, function(index, item) {
		          if(item.flag==true){
			$('#teacherInfo').dataTable().fnAddData([
				'<input type="checkbox" name="ordercheck" id="' + item.id+ '">',
				item.username,
				item.name,
				item.collegeName,
				item.longPhone,
				'<div class="layui-btn  layui-btn-small delete" id="' + item.id+ '"  >删除</div><div class="layui-btn  layui-btn-small forbidden" id="' + item.id+ '">禁用</div>'
			]);
		}
		if(item.flag==false){
			$('#teacherInfo').dataTable().fnAddData([
				'<input type="checkbox" name="ordercheck" id="' + item.id+ '">',
				item.username,
				item.name,
				item.collegeName,
				item.longPhone,
				'<div class="layui-btn  layui-btn-small delete" id="' + item.id+ '"  >删除</div><div class="layui-btn layui-btn-disabled layui-btn-small " id="' + item.id+ '">禁用</div>'
			]);
		}
					
										
				});
				
}

//创建学生列表
function createStudentList(){
	$("#peoplelist").append(

					'<div id=list2>' +

					'<table id="studentInfo" class="display" cellspacing="0" width="100%" >\n' +
					'        <thead>\n' +
					'        <tr>\n' +
					'            <th width="2%"><input id="checkAll" class="checkAll" type="checkbox" value=""></th>\n' +
					'            <th width="15%" id="th_stuid" >学号</th>\n' +
					'            <th width="10%" id="th_stuname" >姓名</th>\n' +
					'            <th width="10%" id="th_stusex">性别</th>\n' +
				
					'            <th width="15%" id="th_academy" >学院</th>\n' +
				
					'            <th width="10%" id="th_class" >班级</th>\n' +
					'            <th width="13%" id="th_stutele" >手机</th>\n' +
					'            <th width="25%" id="th_action" >操作</th>\n' +

					'        </tr>\n' +
					'        </thead>\n' +
					
					'        <tbody style="font-size: 14px">\n' +
					'        </tbody>\n' +
					'    </table>' +
					'</div>');

	            // DataTable
				var table = $('#studentInfo').DataTable({
					ordering: false,
					'paging':false,
					searching:false,
					info:false
				});
}
//学生列表填充数据
function studentTableDataAjax(pageconf){
	if(!pageconf){
		pageconf={};
		pageconf.pageSize=25;
		pageconf.currentPage=1;
	}
	$.ajax({
		type:"get",
		url:ip+"/user?userTypeId=5b88e7a5dc8b5a1a84a96367&page="+pageconf.currentPage+"&size="+pageconf.pageSize+"&keyWord="+searchKeyWords,
		data:{
			
		},
		async:true,
		dataType:"json",
		contentType:" application/json",
		xhrFields:{withCredentials:true},
		crossDomain:true,
		success:function(obj){
			$('#studentInfo').dataTable().fnClearTable(); //清除表格内
			console.log(obj)
			totalcount2=obj.data.totalCount;
			getPage2(pageconf,obj.data.data);
		},
		Error:function(){
			alert("服务器出错");
		}
		
	})
	
	
	
	
}
//给学生列表
function expressstudata(data){
	
	$.each(data, function(index, item) {
				if(item.flag==true){
			$('#studentInfo').dataTable().fnAddData([
				'<input type="checkbox" name="ordercheck">',
				item.username,
						item.name,
						item.gender,
						
						item.collegeName,
						
						item.className,
						item.longPhone,
				'<div class="layui-btn  layui-btn-small delete" id="' + item.id+ '"  >删除</div> <div class="layui-btn  layui-btn-small forbidden"  id="' + item.id+ '"  >禁用</div> '
			]);
		};
		if(item.flag==false){
			$('#studentInfo').dataTable().fnAddData([
				'<input type="checkbox" name="ordercheck">',
				item.username,
						item.name,
						item.gender,
						
						item.collegeName,
						
						item.className,
						item.longPhone,
				'<div class="layui-btn  layui-btn-small delete"  id="' + item.id+ '"  >删除</div><div class="layui-btn layui-btn-disabled layui-btn-small " id="' + item.id+ '"  >禁用</div> '
			]);
		};	
					
										
				});
				
	
	
}







//创建辅导员列表
function creatgraduatestudentList(){
	
	$("#peoplelist").append(
					'<div id=list3>' +

					'<table id="graduateInfo" class="display" cellspacing="0" width="100%">\n' +
					'        <thead>\n' +
					'        <tr>\n' +
					'            <th width="10%"><input id="checkAll" class="checkAll" type="checkbox" value=""></th>\n' +
					'            <th width="10%" id="_class" >学号</th>\n' +
					'            <th width="10%" id="major" >姓名</th>\n' +
                    '            <th width="10%" id="level" >专业</th>\n' +
                    '            <th width="10%" id="level" >学院</th>\n' +
					'            <th width="10%" cotelenumber" >层次</th>\n' +
					'            <th width="10%" id="th_action" >手机号码</th>\n' +
                    '            <th width="30%" id="th_action" >操作</th>\n' +
					'        </tr>\n' +
					'        </thead>\n' +
					'        <tbody style="font-size: 14px">\n' +
					'        </tbody>\n' +
					'    </table>' +
					'</div>');

	var table = $('#graduateInfo').DataTable({
					ordering: false,
					'paging':false,
					searching:false,
					info:false
				});			
	
	
	
}
//学生列表填充数据
function graduateTableDataAjax(pageconf){
	if(!pageconf){
		pageconf={};
		pageconf.pageSize=25;
		pageconf.currentPage=1;
	}
	$.ajax({
		type:"get",
		url:ip+"/user?userTypeId=5b88e7e8dc8b5a1a84a96370&page="+pageconf.currentPage+"&size="+pageconf.pageSize+"&keyWord="+searchKeyWords,
		data:{
			
		},
		async:true,
		dataType:"json",
		contentType:" application/json",
		xhrFields:{withCredentials:true},
		crossDomain:true,
		success:function(obj){
			$('#graduateInfo').dataTable().fnClearTable(); //清除表格内
			console.log(obj)
			totalcount3=obj.data.totalCount;
			getPage3(pageconf,obj.data.data);
		},
		Error:function(){
			alert("服务器出错");
		}
		
	})
	
	
	
	
}
function expressgradata(data){
	
	$.each(data, function(index, item) {
		if(item.flag==true){
					$('#graduateInfo').dataTable().fnAddData([
						'<input type="checkbox" name="ordercheck" id="'+item.id+'">',
						item.username,
						item.name,
						item.major,
						item.collegeName,
						item.level,
						item.longPhone,
						'<div class="layui-btn  layui-btn-small delete"  id="' + item.id+ '"  >删除</div><div class="layui-btn layui-btn-small " id="' + item.id+ '"  >禁用</div> '
					]);
				}
		if(item.flag==false){
					$('#graduateInfo').dataTable().fnAddData([
						'<input type="checkbox" name="ordercheck" id="'+item.id+'">',
						item.username,
						item.name,
						item.major,
						item.collegeName,
						item.level,
						item.longPhone,
						'<div class="layui-btn  layui-btn-small delete"  id="' + item.id+ '"  >删除</div><div class="layui-btn layui-btn-disabled layui-btn-small " id="' + item.id+ '"  >禁用</div> '
					]);
				}
		
		});
			
			
	}


//教师分页操作
function getPage1(pageconf1,data,type){
    layui.use(['laypage', 'layer'], function(){
  	var laypage = layui.laypage
  	,layer = layui.layer;
 		laypage.render({
           	elem: 'demo0',
           	count: totalcount1, //数据总数，从服务端得到
           	curr:pageconf1.currentPage,
			limit:pageconf1.pageSize,
            limits:[6,12,18,24],
			skip:true,
			first:"首页",
			last:"尾页",
			layout:['count','skip', 'prev', 'next'],  
            jump: function(obj, first){
                   console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                    console.log(obj.limit); //得到每页显示的条数
                    page=obj.curr;  //改变当前页码
                    limit=obj.limit;
                    //首次不执行
                    if(!first){
                    	pageconf1.currentPage=obj.curr;
					    pageconf1.pageSize=obj.limit;
		    			teacherTableDataAjax(pageconf1);
		    			
		    		}
                }
            
            });
            console.log(data);
           
   				expressdata(data);
   
            
        });
    }
//学生分页操作
function getPage2(pageconf,data,type){
    layui.use(['laypage', 'layer'], function(){
  	var laypage = layui.laypage
  	,layer = layui.layer;
 		laypage.render({
           	elem: 'demo1',
           	count: totalcount2, //数据总数，从服务端得到
           	curr:pageconf.currentPage,
			limit:pageconf.pageSize,
            limits:[6,12,18,24],
			skip:true,
			first:"首页",
			last:"尾页",
			layout:['count','skip', 'prev', 'next'],  
            jump: function(obj, first){
                   console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                    console.log(obj.limit); //得到每页显示的条数
                    page=obj.curr;  //改变当前页码
                    limit=obj.limit;
                    //首次不执行
                    if(!first){
                    	pageconf.currentPage=obj.curr;
					    pageconf.pageSize=obj.limit;
		    			
		    			studentTableDataAjax(pageconf);
		    		}
                }
            
            });
            console.log(data);
            expressstudata(data);
   
            
        });
    }
//研究生分页操作
function getPage3(pageconf,data,type){
    layui.use(['laypage', 'layer'], function(){
  	var laypage = layui.laypage
  	,layer = layui.layer;
 		laypage.render({
           	elem: 'demo2',
           	count: totalcount3, //数据总数，从服务端得到
           	curr:pageconf.currentPage,
			limit:pageconf.pageSize,
            limits:[6,12,18,24],
			skip:true,
			first:"首页",
			last:"尾页",
			layout:['count','skip', 'prev', 'next'],  
            jump: function(obj, first){
                   console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                    console.log(obj.limit); //得到每页显示的条数
                    page=obj.curr;  //改变当前页码
                    limit=obj.limit;
                    //首次不执行
                    if(!first){
                    	pageconf.currentPage=obj.curr;
					    pageconf.pageSize=obj.limit;
		    			graduateTableDataAjax(pageconf);
		    		}
                }
            
            });
            console.log(data);
            expressgradata(data);
   
            
        });
    }

//获取搜索关键字
function getKeyword(){
	$('#search-form').autocomplete({
		width: 200,
		height: 25,
		onSubmit: function(text){
			searchKeyWords=text;
		    console.log(searchKeyWords);
		  	teacherTableDataAjax();
		    studentTableDataAjax();
		    graduateTableDataAjax();
		    
		}
	});
}
var userId;
var index1;
$(document).on('click','.delete',function(){
			 index1=layer.open({
				type:1,
				title: '提示',
				closeBtn:1,
				skin: 'layui-layer-rim', //加上边框
  				area: ['300px', '150px'], //宽高
				content: '<div style="margin-top: 5%;margin-left:30%;">是否要删除该人员？<br/><br/><input type="button" value="确定"class="layui-btn layui-btn-sm deleteperson"style="margin-left: 30%;background-color:#1e9fff"><input type="button" value="取消"class="layui-btn layui-btn-sm cancle "style="margin-left: 7%;background-color:#ffffff;color:#000000;border-style:solid;border-width:1px;border-color:#f3f3f3;"></div>',
			
			});
		
			 userId=this.id;
			  

		})
$(document).on('click','.cancle',function(){
			parent.layer.close(index1);//关闭当前页
			
			 
		})
//删除按钮
			$(document).on('click', '.deleteperson', function() {
				k = $(this).parents("tr").index() + 1;
			 	$.ajax({
		 			type: "delete",
		 			url: ip + "/user/"+userId,
		 			data: {},
		 			async: true,
		 			xhrFields: {
						withCredentials: true
					},
					crossDomain: true,
		 			dataType: "",
		 			contentType: "application/json",
		 			success: function(res) {
		 				/*window.location.reload();*/
		 				if(res.code==0){
		 					window.location.reload();
		 					layer.msg(res.data);
		 					
		 				}
		 				if(res.code==-1){
		 					layer.msg(res.msg);
		 				}
							
					},
		 			Error: function() {
		 				alert("服务器出错");
		 			}
		 		})
		 	})
			 	
			 	
			 	
			 
function isLogin(){
	$.ajax({
		 				type: "get",
		 				url:ip+"/user/type ",
		 				data: {},
		 				async: true,
		 				dataType: "",
		 				contentType: "application/json",
		 				xhrFields: {
						withCredentials: true
						},
						crossDomain: true,
		 				success: function(res) {
		 					if(res.code==-1){
		 						layui.use('layer', function(){
  									var layer = layui.layer;
  									layer.msg(res.msg);
								});     
		 						
		 						window.location.href="login.html";
		 						console.log(res.msg);
		 					}
						
		 				},
		 				Error: function() {
		 					alert("服务器出错");
		 				}
		 			})
}
//下载excel模板
function downLoad(){
	$.ajax({
		 				type: "get",
		 				url:ip+"/surveyGroup/template ",
		 				data: {},
		 				async: true,
		 				dataType: "",
		 				contentType: "application/json",
		 				xhrFields: {
						withCredentials: true
						},
						crossDomain: true,
		 				success: function(res) {
		 					/*if(res.code==-1){
		 						layui.use('layer', function(){
  									var layer = layui.layer;
  									layer.msg(res.msg);
								});     
		 						
		 						window.location.href="login.html";
		 						console.log(res.msg);
		 					}*/
						
		 				},
		 				Error: function() {
		 					alert("服务器出错");
		 				}
		 			})
}



var index2;
$(document).on('click', '#importPeople', function() {
	index2=layer.open({
		type:1,
		title: '上传文件',
		skin: 'layui-layer-rim', //加上边框
  		area: ['500px', '150px'], 
		content: '<form method="post" id="file" action="" enctype="multipart/form-data;charset=utf-8">'+
		 
		    '<div>'+
		    '<div style="float:left;margin-top: 20px;margin-left: 10px;background-color:#f5f5f5;width: 350px;height: 25px;padding-top: 10px;padding-bottom: 15px;">'+
		    '<a href="javascript:;" class="file">'+
		    '选择文件'+
		    '<input id="excelFile" class="myfile" type="file" name="file" />'+
		    '</a>'+
		    '<div class="filename" style="width:160px;float:right;margin-top: 3px;margin-right: 30%;word-wrap:break-word;">'+
		   
		    '未选择文件夹。'+
		    
		    '</div>'+
		    '</div>'+
		    '<br/><br/>'+
		    '<input type="button" value="上传" style="position:absolute;top:25px;left:400px;"class="layui-btn layui-btn-normal" onclick="uploadFiles();"/>'+
		   	'</div>'+
		    '</form>',
	});
	$(".file").on("change","input[type='file']",function(){
    var filePath=$(this).val();
    if(filePath.indexOf("xls")!=-1){
      
        var arr=filePath.split('\\');
        var fileName=arr[arr.length-1];
        $("#unchose").hide();
        $(".filename").html(fileName);
    }else{
        $(".filename").html("您上传的文件类型有误，请重新选择！");
   
        return false 
    }
})
	
})
function getType(){
	if($("#peoplegroup").val()=="老师"){
    	return "5b88e7e8dc8b5a1a84a96368";
    };
    if($("#peoplegroup").val()=="本科生"){
    	return "5b88e7a5dc8b5a1a84a96367";
    }
    if($("#peoplegroup").val()=="研究生"){
    	return "5b88e7e8dc8b5a1a84a96370";
    }
}
function uploadFiles(){  
// 	var uploadFile = $('#excelFile').get(0).files[0];
	var uploadFile = new FormData($("#file")[0]);
	var userTypeId=getType();
	console.log(userTypeId);
	uploadFile.append("userTypeId",userTypeId);
	
	if("undefined" != typeof(uploadFile) && uploadFile != null && uploadFile != ""){
		$.ajax({
			url: ip+'/user/addUsers',
			type:'POST',
			data:uploadFile,
			async: false,
			xhrFields: {
				withCredentials: true
			},
			crossDomain: true,
			cache: false, 
			contentType: false, //不设置内容类型
			processData: false, //不处理数据
			success:function(data){
				if(data.code==0){
					layer.msg("上传成功！");
					parent.layer.close(index2);
				}
				if(data.code==-1){
					layer.msg(data.msg);
				}
			},
			error:function(){
				alert("上传失败！");
			}
		})
	}else {
		alert("选择的文件无效！请重新选择");
	}
}   
$(document).ready(function(){
	$('.autocomplete-input').attr('placeholder','搜索')
	isLogin()
	downLoad()
	createTeacherList()
	teacherTableDataAjax()
	getKeyword()
	createStudentList()
	studentTableDataAjax()
	creatgraduatestudentList()
	graduateTableDataAjax()
	
	$("#list1").hide();
	$("#list2").hide();
	$("#list3").hide();
	$("#demo0").hide();
	$("#demo1").hide();
	$("#demo2").hide();
	$("#demo").hide();
	$("#peoplegroup").change(function() {
					if($(this).val() == "老师") {
						
						$("#list2").hide();
					    $("#list3").hide();
						$("#list1").show();
                        $("#demo0").show();
						$("#demo1").hide();
						$("#demo2").hide();
						$("#demo").show();
					}
					if($(this).val() == "本科生") {
						
						$("#list1").hide();
						$("#list3").hide();
						$("#list2").show();
						$("#demo1").show();
						$("#demo0").hide();
						$("#demo2").hide();
						$("#demo").show();
					}
					if($(this).val() == "研究生") {
					
						$("#list1").hide();
						$("#list2").hide();
						$("#list3").show();
						$("#demo1").hide();
						$("#demo0").hide();
						$("#demo2").show();
						$("#demo").show();
					}
				    

				});
				
	$('.checkAll').on('click', function () {
            if (this.checked) {
                $(this).attr('checked','checked')
                $("input[name='ordercheck']").each(function () {
                    this.checked = true;
                });
            } else {
                $(this).removeAttr('checked')
                $("input[name='ordercheck']").each(function () {
                    this.checked = false;
                });
            }
        });
			
})
	
layui.use('upload', function() {
				var upload = layui.upload;
				var uploadInst = upload.render({
					elem: '#test1' ,
					url:ip+'/user/addUsers',
					accept: 'file',
					data: {
  						userTypeId: function(){
    						if($("#peoplegroup").val()=="老师")
    						{
    							return "5b88e7e8dc8b5a1a84a96368";
    						};
    						if($("#peoplegroup").val()=="学生")
    						{
    							return "5b88e7a5dc8b5a1a84a96367";
    						}
    						
  						}
					},
       
					before: function(){
               			 console.log('接口地址：'+ this.url, this.item, {tips: 1});
            		},
					done: function(res) {
						if(res.code == 0){
							 console.log("上传成功");
						    layer.msg('人员导入成功请刷新后查看！');
						}
				        else{
				        	layer.msg(res.msg);
				        }
					    					    
											    
					},
					error: function() {
						
						layer.msg('请联系管理员');
					}
				});
			});